﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace S1882I
{
    public class S1882IReWr
    {

        //定义宏
        const int MAX_TAG_DATA_LEN = 0xFF;
        const int Y_ERR_INPROGRESS = 0x80;

        // Status Error Code Definitions
        const int ERR_NONE = 0;  // No errors faults encountered

        /// <summary>
        ///  模块库函数链接-start*************************************************************************************
        /// </summary>
        ///  
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_Open(ref int hCom, String com_port);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_Close(int hCom, byte RAddr);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SetBaudRate(ref int hCom, ulong BaudRate);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysSetBaudRate(int hCom, byte RAddr, byte BaudRateIndex);


        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufFormatEX(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufCLRAll(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufGetTagNum(int hCom, byte RAddr, ref byte TagCount);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufGetVarTag(int hCom, byte RAddr, byte InTagCount, ref byte OutTagCount, ref byte[] TagData);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufGetOneAndClear(int hCom, byte RAddr, ref byte TagData);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufGetOneNoClear(int hCom, byte RAddr, ref byte TagData);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_BufGetOneACK(int hCom, byte RAddr);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFSet(int hCom, byte RAddr, int RF);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysGPIO(int hCom, byte RAddr, byte type, byte port, byte inStatus, ref byte outPort, ref byte outStatus);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFQuery(int hCom, byte RAddr, ref int RF);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFOff(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFOn(int hCom, byte RAddr);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFFrequencySet(int hCom, byte RAddr, byte inFrequency);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFFrequencyQuery(int hCom, byte RAddr, ref byte outFrequency, ref byte outFreqType);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFModIndexSet(int hCom, byte RAddr, byte inModIndex);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFModIndexQuery(int hCom, byte RAddr, ref byte outModIndex);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFAntennaQuantitySet(int hCom, byte RAddr, byte inAntennaQuantity);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFAntennaQuantityQuery(int hCom, byte RAddr, ref byte outAntennaQuantity);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFCurrentAntennaSet(int hCom, byte RAddr, byte AntennaID);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFCurrentAntennaQuery(int hCom, byte RAddr, ref byte outAntennaID);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFAntennaCycle(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysRFAntennaCycleEnd(int hCom, byte RAddr);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysReset(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysGetRStatus(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysGetFirmwareRevision(int hCom, byte RAddr, ref byte MainVersion, ref byte MinorVersion);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysWorkModeSet(int hCom, byte RAddr, byte WorkMode);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysWorkModeQuery(int hCom, byte RAddr, ref byte WorkMode);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysTagIDDiscriminatSet(int hCom, byte RAddr, byte DiscriminateMode);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysTagIDDiscriminateQuery(int hCom, byte RAddr, ref byte DiscriminateMode);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysBufTypeSelSet(int hCom, byte RAddr, byte BufType);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysBufTypeSelQuery(int hCom, byte RAddr, ref byte BufType);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysMACSet(int hCom, byte RAddr, byte[] inMAC);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysMACQuery(int hCom, byte RAddr, byte[] outMAC);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysMACCancel(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysUACSet(int hCom, byte RAddr, byte[] inUAC);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysUACQuery(int hCom, byte RAddr, byte[] outUAC);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysUACCancel(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysTagAuthorizationSet(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysTagAuthorizationQuery(int hCom, byte RAddr, ref byte outTagAC);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SysTagAuthorizationCancel(int hCom, byte RAddr);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_SetReaderAddress(int hCom, byte RAddr, byte ReaderAddress);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_GetReaderAddress(int hCom, byte RAddr, ref byte ReaderAddress);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_GetManufactory(int hCom, byte RAddr, byte[] Manufactory);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_GetProduceType(int hCom, byte RAddr, byte[] ProductType);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_GetProductDate(int hCom, byte RAddr, byte[] ProductDate);
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDpub_GetProductSN(int hCom, byte RAddr, byte[] ProductSN);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_End(int hCom, byte RAddr);

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_SingleRead(int hCom, byte RAddr,
                                       byte QValue,
                                       byte Bank,
                                       byte Point,
                                       byte ReadLength,
                                       byte MaskLenght,
                                       byte[] Mask,
                                       ref byte TagCount,
                                       ref byte DataLength,
                                       byte[] Data
                                       );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_SingleReadID(int hCom, byte RAddr,
                                         byte QValue,
                                         byte MaskLength,
                                         byte[] Mask,
                                         ref byte TagCount,
                                         ref byte IDBitCount,
                                         byte[] TagID
                                         );
        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_MultiRead(int hCom, byte RAddr,
                                      byte QValue,
                                      byte Bank,
                                      byte Point,
                                      byte ReadLength,
                                      byte MaskLength,
                                      byte[] Mask
                                      );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_MultiReadID(int hCom, byte RAddr,
                                        byte QValue,
                                        byte MaskLength,
                                        byte[] Mask,
                                        ref byte TagCount
                                        );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_Write(int hCom, byte RAddr,
                                  byte QValue,
                                  byte Bank,
                                  byte Point,
                                  byte DataLength,
                                  byte[] Data
                                  );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_WriteID(int hCom, byte RAddr,
                                    byte QValue,
                                    byte IDBitCount,
                                    byte[] TagID
                                    );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_WriteWithID(int hCom, byte RAddr,
                                    byte QValue,
                                    byte IDBitCount,
                                    byte[] TagID,
                                    byte Bank,
                                    byte Point,
                                    byte DataLength,
                                    byte[] Data
                                    );


        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_Lock(int hCom, byte RAddr,
                                 byte QValue,
                                 byte[] Password,
                                 byte Select,
                                 byte Action,
                                 byte IDBitCount,
                                 byte[] TagID
                                 );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_Kill(int hCom, byte RAddr,
                                 byte QValue,
                                 byte[] Password,
                                 byte IDBitCount,
                                 byte[] TagID
                                 );

        [DllImport("SeRFIDAPI02.dll")]
        static extern short SeRFIDGen2_Erase(int hCom, byte RAddr,
                                  byte QValue,
                                  byte Bank,
                                  byte Point,
                                  byte EraseLength,
                                  byte IDBitCount,
                                  byte[] TagID
                                  );


        private int g_hcom;
        private bool btnConnectFlag = true;
        private bool btnReadFlag = true;
              //操作串口句柄
        private byte g_RAddr = 0xFF;   //读写器地址
        byte[] tags_id = new byte[MAX_TAG_DATA_LEN];
        byte[] tempdata = new byte[MAX_TAG_DATA_LEN - 1];
        byte[] mask1 = new byte[16];
        byte[] tags_data = new byte[MAX_TAG_DATA_LEN];

        private string GetPower()
        {
            int rf_power = 0;
            int ps = 0;

            string str;
            ps = SeRFIDpub_SysRFQuery(g_hcom, g_RAddr, ref rf_power);
            if (ERR_NONE == ps)
            {
                str = System.String.Format("RF Power is {0:d02} dBm!", rf_power);
                //comboRf.SelectedIndex = ((rf_power) / 5 - 20);
            }
            else
            {
                str = System.String.Format("RF Power getting is fail! 0x{0:X02}", ps);
            }

            return str;
        }

        public short Connect_Open(string com_port)
        {
            short openStatus = 0;
           // string strPort = System.String.Format("COM{0}", port + 1);
            int ps = 0;
            string str;
            byte[] major = new byte[20];
            byte[] minor = new byte[20];
            byte[] patch = new byte[20];
            ps = SeRFIDpub_Open(ref g_hcom, com_port);
            if (ps == ERR_NONE)
            {
                ps = SeRFIDpub_SysGetFirmwareRevision(g_hcom, g_RAddr, ref major[0], ref minor[0]);
                if (ps == ERR_NONE)
                {
                    string sVersion;
                    sVersion = System.String.Format("{0:X02}.{1:X02}", major[0], minor[0]);
                    str = System.String.Format("Reader started! Firmware is {0}", sVersion);

                    GetPower();     //获取功率
                    //MessageBox.Show(str);
                    return openStatus;
                }
                else
                {
                    openStatus = -1;
                    str = System.String.Format("Get reader firmware is failed!{0:X02}", ps);
                    //MessageBox.Show(str);
                    SeRFIDpub_Close(g_hcom, g_RAddr);
                    g_hcom = 0;
               
                }
            }
            else
            {
                openStatus = -1;
                str = System.String.Format("Connect com port is failed! {0:X02}", ps);
               // MessageBox.Show(str);
                SeRFIDpub_Close(g_hcom, g_RAddr);
                g_hcom = 0;
               
            }
            return openStatus;

        }
        public short Connect_Close()
        {
            short a = SeRFIDpub_Close(g_hcom, g_RAddr);
            //g_hCom = 0;
            //MessageBox.Show("Disconnect Com port successfully");
            //return true;
           // short closeStatus = rfidapi03_close(g_hcom);
            g_hcom = 0;
            return a;
        }
        byte QValue = 4;
        byte Point = 0;
        private TagCountId ReadTagData(int bankID, int len)
        {
             //Q值
            byte Bank = (byte)bankID;
            //byte Point = (byte)pointID;
            byte ReadLength = (byte)len;
            byte MaskLenght = 0;//不匹配
            byte[] Mask = new byte[10];

            byte TagCount = 0;
            byte DataLength = 0;
            byte[] Data = new byte[MAX_TAG_DATA_LEN];
            int ps = SeRFIDGen2_SingleRead(g_hcom, g_RAddr, QValue, Bank, Point, ReadLength, MaskLenght, Mask, ref TagCount, ref DataLength, Data);
            TagCountId tci = new TagCountId();
            if (ps == ERR_NONE)
            {
                int i = 0, j = 0;
                byte[] tempdata = new byte[DataLength+1];

                for (i = 0; i < TagCount; i++)
                {
                    for (j = 1; j <= DataLength; j++)
                    {
                        tempdata[j] = Data[j-1 ];
                    }
                    tempdata[0] = DataLength;
                    tci.tags_id = tempdata;
                    tci.iDBitCount = 1;
                    break;
                }
            }
            return tci;

        }
        

        public TagCountId ReadID()                 //读EPCID
        {
            return ReadTagData(1,12);
        }
        public TagCountId ReadTID()                 //读TID
        {
            return ReadTagData(2, 12);
        }
        public TagCountId ReadUser()               //读用户区
        {
           
            return ReadTagData(3,12);
        }

        public short WriteID(string strhex)     //写EPCID
        {

            byte bank = 1;
              byte  write_len = 12;
           
            byte[] tagid = new byte[20];
            short writeidStatus = 0;

            byte[] bydata = new byte[12];
            if (strhex.Length < 24)
            {
                if (strhex.Length % 2 != 0)
                    strhex = strhex + "0";
                for (int i = 0; i < strhex.Length / 2; i++)
                    bydata[i] = Convert.ToByte(strhex.Substring(i * 2, 2), 16);
            }
            else
            {
                for (int i = 0; i < 12; i++)
                    bydata[i] = Convert.ToByte(strhex.Substring(i * 2, 2), 16);
            }

           // SeRFIDGen2_Write(g_hcom, g_RAddr, QValue, bank, Point, write_len, bydata);

            for (int j = 0; j < 10; j++)
            {
               // writeidStatus = rfidapi03_6c_write(g_hcom, bank, offset, write_len, 0, ref tagid[0], ref bydata[0], ref ms_count);
               writeidStatus= SeRFIDGen2_Write(g_hcom, g_RAddr, QValue, bank, Point, write_len, bydata);
                if (writeidStatus == 0)
                    break;
            }
            return writeidStatus;
        }

        public short WriteUser(string strhex)     //写USER区
        {
            
            byte bank = 3,  write_len = 14;
            byte[] tagid = new byte[20];
            short writeidStatus = 0;
            if (strhex.Length % 2 != 0)
                strhex = strhex + "0";
            byte[] bydata = new byte[28];
            //byte[] bydata = new byte[strhex.Length / 2+1];
            if (strhex.Length <= 56)
            {
                for (int i = 0; i < strhex.Length / 2; i++)
                {
                    bydata[i] = Convert.ToByte(strhex.Substring(i * 2, 2), 16);
                }
            }
            else
            {
                for (int i = 0; i < 28; i++)
                {
                    bydata[i] = Convert.ToByte(strhex.Substring(i * 2, 2), 16);
                }
            }
            for (int j = 0; j < 10; j++)
            {
                writeidStatus = SeRFIDGen2_Write(g_hcom, g_RAddr, QValue, bank, Point, write_len, bydata);
              //  writeidStatus = rfidapi03_6c_write(g_hcom, bank, offset, write_len, 0, ref tagid[0], ref bydata[0], ref ms_count);
                if (writeidStatus == 0)
                    break;
            }
            return writeidStatus;
        }
    }

    public class TagCountId
    {
        //public int tagcount;
        public int iDBitCount;   //标签数据长度(单位：byte)
        public byte[] tags_id;   //标签数据
    }
   

}
